import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Message, Button } from '@teamix/ui';
import exceed from 'utils/apimap';
import { YunxiaoIcon } from '@alife/devops-ui';
import './index.scss';
import intl from '../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

const prefix = 'unfreeze-ip-dialog';

export default class ProjectModal extends React.Component {
  static propTypes = {
    defaultNamespaceId: PropTypes.string,
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
    isModalOpen: PropTypes.bool,
    isSubgroup: PropTypes.bool,
    tbProjectName: PropTypes.string,
    okFn: PropTypes.func,
    onCreateSuccess: PropTypes.func,
  };

  static defaultProps = {
    defaultNamespaceId: '',
    trigger: null,
    closeModal: () => {},
    tbProjectName: '',
    okFn: () => {}, // 新建完成的回调
    onCreateSuccess: () => {}, // codeup新建库成功回调
    isSubgroup: false,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      isModalOpen: false,
      codeTime: 0,
      isSendingCode: false,
    };

    this.timer = null;
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  getCode = () => {
    if (this.state.codeTime) {
      return;
    }
    this.sendCode(() => {
      this.timer = setInterval(() => {
        const { codeTime } = this.state;
        this.setState({
          codeTime: codeTime === 0 ? 59 : codeTime - 1,
        });

        codeTime === 1 && clearInterval(this.timer);
      }, 1000);
    });
  };

  sendCode = (cb) => {
    this.setState({
      isSendingCode: true,
    });

    exceed
      .fetch({
        api: 'organization.ip.send_cancel_token',
      })
      .then(() => {
        cb && cb();
        Message.success({
          className: 'hack_send_code_message',
          title: intl.get({
            id: 'code-assets.components.unfreezeIpModal.VerificationCodeSentSuccessfully',
            defaultMessage: '验证码发送成功',
          }),
        });

        this.setState({
          isSendingCode: false,
        });
      })
      .fail(() => {
        this.setState({
          isSendingCode: false,
        });
      });
  };

  onDialogOk = () => {
    const { submitting } = this.state;
    if (submitting) {
      return;
    }
    const { organization } = window.FORCE;
    const formData = this.field.getValues();
    this.setCodeError(formData.verification_code);
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        formData.organization_id = organization.id;
        this.unfreezeIp(formData);
      }
    });
  };

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  unfreezeIp = (data) => {
    const { onSuccess } = this.props;
    exceed
      .fetch({
        api: 'organization.ip.cancel',
        data,
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.components.unfreezeIpModal.IpAddressWhitelistVerificationDisabled',
            defaultMessage: 'IP 白名单验证关闭成功',
          }),
        });

        this.setState({
          submitting: false,
        });

        this.onClose();
        onSuccess && onSuccess();
      })
      .fail(() => {
        this.setState({
          submitting: false,
        });
      });
  };

  changeCode = (value) => {
    this.setState({
      verification_code: value,
    });

    this.field.setValue('verification_code', value);
    this.setCodeError(value);
  };

  setCodeError = (value) => {
    this.field.setError(
      'verification_code',
      value
        ? ''
        : intl.get({
            id: 'code-assets.components.unfreezeIpModal.ThisParameterIsRequired',
            defaultMessage: '该项为必填项',
          }),
    );
  };

  render() {
    const { init } = this.field;
    const { codeTime, isSendingCode, verification_code } = this.state;
    const { user } = window.FORCE;

    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            className={`${prefix}`}
            title={intl.get({
              id: 'code-assets.components.unfreezeIpModal.DisableIpWhitelistVerification',
              defaultMessage: '关闭 IP 白名单验证',
            })}
            visible
            onClose={this.onClose}
            onCancel={this.onClose}
            okProps={{ loading: this.state.submitting }}
            onOk={this.onDialogOk}
            style={{ width: 500 }}
          >
            <Form labelAlign="top" field={this.field} className="unfreeze-ip-form">
              <FormItem
                label={intl.get({
                  id: 'code-assets.components.unfreezeIpModal.Authentication',
                  defaultMessage: '身份验证',
                })}
                required
                {...formItemLayout}
              >
                <div className="email-help">
                  {intl.get({
                    id: 'code-assets.components.unfreezeIpModal.UseYourPrimaryEmailAddress',
                    defaultMessage: '通过您的主邮箱进行管理员身份验证',
                  })}
                </div>
                <div>
                  <Input value={user.email || ''} style={{ width: '100%' }} disabled />
                </div>
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.components.unfreezeIpModal.VerificationCode',
                  defaultMessage: '验证码',
                })}
                required
                {...formItemLayout}
                className={this.field.getState('verification_code') === 'error' ? 'has-error' : ''}
                help={
                  this.field.getState('verification_code') === 'error' ? (
                    <div>
                      <YunxiaoIcon type="delete-fill" />
                      <span className="next-form-item-help-text">
                        {this.field.getError('verification_code')}
                      </span>
                    </div>
                  ) : (
                    ''
                  )
                }
              >
                <div className="code-container">
                  <Input.Group
                    addonAfter={
                      <Button type="normal" loading={isSendingCode} onClick={this.getCode}>
                        {codeTime
                          ? `${codeTime} s`
                          : intl.get({
                              id: 'code-assets.components.unfreezeIpModal.ObtainVerificationCode',
                              defaultMessage: '获取验证码',
                            })}
                      </Button>
                    }
                  >
                    <Input
                      value={verification_code}
                      onChange={this.changeCode}
                      placeholder={intl.get({
                        id: 'code-assets.components.unfreezeIpModal.EnterAVerificationCode',
                        defaultMessage: '请输入验证码',
                      })}
                    />
                  </Input.Group>
                </div>
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.components.unfreezeIpModal.ReasonForClosing',
                  defaultMessage: '关闭原因',
                })}
                required
                {...formItemLayout}
              >
                <Input.TextArea
                  {...init('close_reason', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.components.unfreezeIpModal.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                    ],
                  })}
                  placeholder={intl.get({
                    id: 'code-assets.components.unfreezeIpModal.EnterTheReasonForDisabling',
                    defaultMessage: '请输入关闭原因',
                  })}
                />
              </FormItem>
              <div>
                <Message
                  title={intl.get({
                    id: 'code-assets.components.unfreezeIpModal.NoteAfterTheIpAddress',
                    defaultMessage: '注意：关闭 IP 白名单后，代码库部署密钥将同时失效',
                  })}
                  type="warning"
                />
              </div>
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              this.props.trigger.props.onClick && this.props.trigger.props.onClick(e);
              this.showModal();
            },
          })}
      </React.Fragment>
    );
  }
}
